import random
from datetime import datetime
from urllib.parse import parse_qs
from collections import OrderedDict
from django.shortcuts import render, redirect
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import HttpResponse

from www import models
from utils.pay_ali import AliPay
from utils.vod_ali import get_play_auth


def basic(request):
    course_list = models.Course.objects.filter(category=1).order_by('order')
    context = {
        "course_list": course_list,
        "count": course_list.count(),
    }
    return render(request, 'course_list.html', context)


def spider(request):
    course_list = models.Course.objects.filter(category=2)
    context = {
        "course_list": course_list,
        "count": course_list.count(),
    }
    return render(request, 'course_list.html', context)


def android(request):
    course_list = models.Course.objects.filter(category=3)
    context = {
        "course_list": course_list,
        "count": course_list.count(),
    }
    return render(request, 'course_list.html', context)


def office(request):
    course_list = models.Course.objects.filter(category=4)
    return render(request, 'course_list.html')


def web(request):
    course_list = models.Course.objects.filter(category=5)
    return render(request, 'course_list.html')


"""
    1 测试01 10 1 第1章 轨迹相关
    2 测试02 11 1 第1章 轨迹相关
    3 测试03 11 1 第2章 协议相关
    4 测试04 11 1 第2章 协议相关
    
{
    "第1章 轨迹相关":[
        {"id": 1, "title": 测试01, "duration": "10:33"},
        2 测试02 11 1 第1章 轨迹相关
    ],
    "第2章 轨迹相关":[
        {"id": 1, "title": 测试01, "duration": "10:33"},
        2 测试02 11 1 第1章 轨迹相关
    ]
}
"""


def get_play_info(queryset):
    video_count = 0
    total_duration = 0

    play_dict = OrderedDict()
    for row in queryset:
        mm, ss = divmod(row.duration, 60)
        duration_string = "%02d:%02d" % (mm, ss)

        play_dict.setdefault(row.chapter.title, [])
        play_dict[row.chapter.title].append({"id": row.id, "title": row.title, "duration": duration_string})
        total_duration += row.duration
        video_count += 1
    # 总课时
    _, total_seconds = divmod(total_duration, 60)
    total_hour, total_minute = divmod(_, 60)
    total_duration_string = "%02d:%02d:%02d" % (total_hour, total_minute, total_seconds)

    return video_count, play_dict, total_duration_string


def play(request, cid, video_id):
    # 1.未登录，先登录
    if not request.user:
        return redirect('wx_login')

    # 2.用户已被拉黑
    user_object = models.User.objects.filter(id=request.user.id, status=1).first()
    if not user_object:
        return render(request, 'forbidden.html')

    # 3.查询课程是否存在
    course_object = models.Course.objects.filter(id=cid).first()
    if not course_object:
        return redirect("index")

    # 4.获取当前课程下所有的视频列表 【课程】 -> 章节 -> 视频
    queryset = models.Video.objects.filter(course_id=cid).select_related("chapter") \
        .order_by("chapter__order", "order") \
        .only("id", "title", "duration", "course_id", "chapter__title")

    video_count, play_dict, total_duration_string = get_play_info(queryset)

    context = {
        "video_count": video_count,
        "play_dict": play_dict,
        "total_duration_string": total_duration_string,
        "course_object": course_object,
    }

    # 用户非VIP，展示页面（只有列表+没有视频）
    if user_object.user_type == 0:
        return render(request, 'course_play.html', context)

    # 是VIP会员，播放视频+切换播放视频  video_id=0  video_id=视频ID   instance.vid
    instance = queryset.filter(id=video_id).first() if video_id else queryset.first()
    context['instance'] = instance

    # 课程下没有找到对应要播放的视频
    if not instance:
        return render(request, 'course_play_vip.html', context)

    # 如果有视频，根据vid获取对应的playauth，视频的播放
    play_auth = get_play_auth(instance.vid)
    context.update({"vid": instance.vid, 'play_auth': play_auth})
    return render(request, 'course_play_vip.html', context)


def vip(request):
    amount = settings.VIP_PRICE
    user_object = None if not request.user else models.User.objects.filter(id=request.user.id).first()
    if request.method == "GET":
        return render(request, 'vip.html', {"amount": amount, "user_object": user_object})

    # 去购买VIP
    # 1.用户未登录，先登录
    if not request.user:
        return redirect("wx_login")

    # 2.用户被删除
    if not user_object:
        return redirect("wx_login")

    # 3.用户已是VIP
    if user_object.user_type == 1:
        return redirect("vip")

    # 4.引导购买（生成订单-待支付、跳转支付页面）
    # https://opendocs.alipay.com/support/01rfuw
    # https://opendocs.alipay.com/open/59da99d0_alipay.trade.page.pay?pathHash=e26b497f&scene=22
    ctime_string = datetime.now().strftime("%Y%m%d%H%M%S%f")
    date_ticket = ctime_string[0:8]

    instance = models.Order.objects.filter(
        date_ticket=date_ticket, status=1, user_id=request.user.id
    ).order_by("-id").first()

    if not instance:
        order_id = f'{ctime_string}{random.randint(1000, 9999)}'
        instance = models.Order.objects.create(
            date_ticket=date_ticket, oid=order_id, amount=amount, user_id=request.user.id
        )

    # 5.生成支付宝链接+跳转去支付
    title = "5xClass-IT自学百年大会员"
    pay_url = AliPay().pay_url(instance.oid, float(instance.amount), title)
    return redirect(pay_url)


@csrf_exempt
def ali_notify(request):
    if request.method != "POST":
        return redirect("wx_login")

    body_str = request.body.decode('utf-8')
    post_data = parse_qs(body_str)
    post_dict = {}
    for k, v in post_data.items():
        post_dict[k] = v[0]

    sign = post_dict.pop('sign', None)
    if "sign_type" in post_dict:
        post_dict.pop('sign_type', None)

    verify = AliPay().verify(post_dict, sign)
    if not verify:
        return HttpResponse("failure", status=403)

    out_trade_no = post_dict['out_trade_no']

    ctime = datetime.now()
    instance = models.Order.objects.filter(oid=out_trade_no, status=1).first()
    if not instance:
        return HttpResponse("fail", status=403)

    instance.status = 2
    instance.pay_date = ctime
    instance.save()
    models.User.objects.filter(id=instance.user_id, user_type=0).update(user_type=1, vip_date=ctime)
    return HttpResponse("success")
